import express from 'express';
import moment from 'moment';
import wyApi from '../../lib/wyapi'; // 维易接口API
import tbApi from '../../lib/tbapi'; // 淘宝接口API
import { Cashgift, User } from '../../modal/index'; // 数据库实体类
import { statusList, sequelizeStatus } from '../../common/status'; // 状态码对照
import CONFIG from '../../../config/config.config'
import baseDao from '../../lib/baseDao'; // 用于获取实例化的sequelize
import { checkPermission, reduceMoney, sendMuban } from '../../utils/utils'; // 工具类

const router = express.Router();
const minLevel = 0; // 允许调用接口的最低等级

router.post('/', async function (Request, Response, next) {
  let param = Request.body
  const transaction = await baseDao.sequelize.transaction() // 事务
  let gold = 0 // 用户账户余额
  let cashgiftType = '' // 淘礼金高佣金CPS类型
  await checkPermission(Request, Response, minLevel).then(res => {
    param.userId = res.id
    param.openId = res.openId
    gold = res.gold
  })
  let hasNull = false;
  Object.keys(param).some(item => {
    if (!param[item] || param[item] === '') {
      hasNull = true;
      return true;
    }
  })
  if (hasNull) {
    Response.status(300).send({ message: "对不起，请将表单填写完整后提交" });
    return;
  } else if (Number(param.rightsPrice * 10) > gold) {
    Response.status(300).send({ message: "对不起，礼金金额不可高于您的积分余额" });
    return;
  }

  // 获取高佣类型
  let typeParam = {
    vekey: CONFIG.vekey,
    para: param.goodsId
  }
  await getCashgiftType(typeParam, transaction, Response).then(res => {
    cashgiftType = res.campaign_name
  })

  // 获取淘礼金url
  let urlParam = {
    method: 'taobao.tbk.dg.vegas.tlj.create', // 创建淘礼金
    campaign_type: cashgiftType, // CPS佣金计划类型
    adzone_id: CONFIG.adzoneIdWeb,// 网站渠道pid中的最后一段！
    item_id: param.goodsId,// 宝贝id
    total_num: param.rightsNumber, // 淘礼金个数
    name: param.rightsName, // 淘礼金名称
    user_total_win_num_limit: 1, // 单用户累计中奖次数上限
    security_switch: true, // 安全开关
    per_face: Number(param.rightsPrice), // 单个淘礼金面额，支持两位小数，单位元
    use_end_time: param.rightsEndTime, // 使用结束日期
    use_end_time_mode: param.rightsEndTimeMode, // 结束日期的模式,1:相对时间，2:绝对时间
    send_start_time: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'), // 发放开始时间
  }
  console.log('获取淘礼金参数', urlParam)
  await getCashgiftUrl(urlParam, transaction, Response).then(res => {
    param.rightsId = res.tbk_dg_vegas_tlj_create_response.result.model.rights_id
    param.rightsUrl = res.tbk_dg_vegas_tlj_create_response.result.model.send_url
  })

  // 转换为淘口令
  let tklParam = {
    method: 'taobao.tbk.tpwd.create', // 生成淘口令
    text: param.rightsName, // 口令弹框内容
    url: param.rightsUrl,// 宝贝id
  }
  await getCashgiftTkl(tklParam, transaction, Response).then(res => {
    param.rightsTkl = res.tbk_tpwd_create_response.data.model
  })

  // 账户扣款
  let payParam = {
    userId: param.userId,
    title: '创建礼金',
    originGold: gold,
    // price: Number(param.rightsPrice), // 单个淘礼金面额，支持两位小数，单位元
    // number: Number(param.rightsNumber), // 淘礼金个数
    reduceGold: Number(param.rightsPrice) * Number(param.rightsNumber) * 10,
  }
  await reduceMoney(payParam, transaction, Response).then(res => {
    console.log('扣款后积分：', res)
  })

  // 插入数据库
  Cashgift.Modal.create(param, { transaction: transaction }).then(async res => {
    if (res && res.id) {
      await transaction.commit() // 提交事务
      if (param.formId) {
        let mubanParam = {
          page: param.page, // 点击模板跳转页面
          formId: param.formId,
          openId: param.openId,
          templateId: CONFIG.cashgiftId, // 淘礼金模板ID
          data: {
            keyword1: {
              value: `${payParam.reduceGold}积分`
            },
            keyword2: {
              value: param.dtitle
            },
            keyword3: {
              value: `截至${moment(param.rightsEndTime).format('YYYY-MM-DD')} 23:59:59`
            },
          }
        }
        sendMuban(mubanParam, Response) // 发送模板消息
      }
      Response.json({
        data: param.rightsTkl,
        message: "success"
      });
    } else {
      await transaction.rollback() // 回滚
      Response.status(300).send({ message: "创建淘口令失败，插入数据为空" });
    }
  }).catch(async err => {
    console.log(err)
    await transaction.rollback() // 回滚
    Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
  });
});

function getCashgiftType(typeParam, transaction, Response) {
  // 获取高佣类型
  return new Promise((resolve, reject) => {
    wyApi.cashgiftType(typeParam).then(async res => {
      if (res.msg) {
        // 接口返回出错信息
        console.log(res.msg, '获取高佣类型')
        await transaction.rollback() // 回滚
        Response.status(300).send({ message: res.msg });
      } else {
        resolve(res)
      }
    })
  })
}

function getCashgiftUrl(urlParam, transaction, Response) {
  // 获取淘礼金URL
  return new Promise((resolve, reject) => {
    tbApi.index(urlParam).then(async res => {
      if (res.error_response) {
        // 接口返回出错信息
        console.log(res.error_response, '获取淘礼金URL')
        await transaction.rollback() // 回滚
        Response.status(300).send({ message: res.error_response.sub_msg });
      } else if (!res.tbk_dg_vegas_tlj_create_response.result.success) {
        // 接口返回出错信息
        console.log(res.tbk_dg_vegas_tlj_create_response, '获取淘礼金URL')
        await transaction.rollback() // 回滚
        Response.status(300).send({ message: res.tbk_dg_vegas_tlj_create_response.result.msg_info });
      } else {
        resolve(res)
      }
    })
  })
}

function getCashgiftTkl(tklParam, transaction, Response) {
  // 转换为淘口令
  return new Promise((resolve, reject) => {
    tbApi.index(tklParam).then(async res => {
      if (res.error_response) {
        // 接口返回出错信息
        console.log(res.error_response, '转换为淘口令')
        await transaction.rollback() // 回滚
        Response.status(300).send({ message: res.error_response.sub_msg });
      } else {
        resolve(res)
      }
    })
  })
}

module.exports = router;